package com.quanxiaoha.xiaohashu.kv.biz.service.impl;


import com.quanxiaoha.framework.common.exception.BizException;
import com.quanxiaoha.framework.common.response.Response;
import com.quanxiaoha.xiaohashu.kv.biz.domain.dataobject.NoteContentDO;
import com.quanxiaoha.xiaohashu.kv.biz.domain.repository.NoteContentRepository;
import com.quanxiaoha.xiaohashu.kv.biz.service.NoteContentService;
import com.quanxiaoha.xiaohashu.kv.dto.req.AddNoteContentReqDTO;
import com.quanxiaoha.xiaohashu.kv.dto.req.DeleteNoteContentReqDTO;
import com.quanxiaoha.xiaohashu.kv.dto.req.FindNoteContentReqDTO;
import com.quanxiaoha.xiaohashu.kv.dto.rsp.FindNoteContentRspDTO;
import com.quanxiaoha.xiaohashu.kv.enums.ResponseCodeEnum;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.UUID;

/**
 * @Author: jingyan_liu
 * @CreateTime: 2025-07-25
 * @Description:
 * @Version: 1.0
 */

@Service
@Slf4j
public class NoteContentServiceImpl implements NoteContentService {
	
	@Resource
	private NoteContentRepository noteContentRepository;
	
	
	@Override
	public Response<?> addNoteContent(AddNoteContentReqDTO addNoteContentReqDTO) {
		// 笔记内容 UUID
		String uuid = addNoteContentReqDTO.getUuid();
		// 笔记内容
		String content = addNoteContentReqDTO.getContent();
		
		// 构建数据库 DO 实体类
		NoteContentDO nodeContent = NoteContentDO.builder()
				.id(UUID.fromString(uuid))
				.content(content)
				.build();
		
		// 插入数据
		noteContentRepository.save(nodeContent);
		log.info("插入笔记内容数据: {}", nodeContent);
		
		return Response.success();
	}
	
	@Override
	public Response<FindNoteContentRspDTO> findNoteContent(FindNoteContentReqDTO findNoteContentReqDTO) {
		// 笔记 ID
		String uuid = findNoteContentReqDTO.getUuid();
		// 根据笔记 ID 查询笔记内容
		Optional<NoteContentDO> optional = noteContentRepository.findById(UUID.fromString(uuid));
		log.info("根据笔记 ID 查询笔记内容: {}", uuid);
		
		// 若笔记内容不存在
		if (optional.isEmpty()) {
			throw new BizException(ResponseCodeEnum.NOTE_CONTENT_NOT_FOUND);
		}
		
		NoteContentDO noteContentDO = optional.get();
		// 构建返参 DTO
		FindNoteContentRspDTO findNoteContentRspDTO = FindNoteContentRspDTO.builder()
				.uuid(noteContentDO.getId())
				.content(noteContentDO.getContent())
				.build();
		
		return Response.success(findNoteContentRspDTO);
	}
	
	@Override
	public Response<?> deleteNoteContent(DeleteNoteContentReqDTO deleteNoteContentReqDTO) {
		// 笔记 ID
		String uuid = deleteNoteContentReqDTO.getUuid();
		// 删除笔记内容
		noteContentRepository.deleteById(UUID.fromString(uuid));
		log.info("删除笔记内容数据: {}", uuid);
		return Response.success();
	}
}
